package models

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
)

type GinCookie struct{}

// 写入cookie
func (g GinCookie) Set(context *gin.Context, key string, value interface{}) {
	bytes, err1 := json.Marshal(value)
	// cookie采用DES加密
	desKey := []byte("zj123456")            // 密钥
	encData, _ := DesDecrypt(bytes, desKey) // 返回的是加密后的字节切片

	if err1 != nil {
		fmt.Println("cookie转换出错")
		return
	}
	context.SetCookie(key, string(encData), 3600, "/", context.Request.Host, false, true)
}

// 获取cookie
func (g GinCookie) Get(context *gin.Context, key string, obj interface{}) bool {
	desKey := []byte("zj123456") // 密钥
	valueStr, err1 := context.Cookie(key)
	if err1 == nil && valueStr != "" && valueStr != "[]" {
		decodeStr, err := DesDecrypt([]byte(valueStr), desKey) // 做des解密
		if err != nil {
			return false
		}
		err2 := json.Unmarshal(decodeStr, obj)
		return err2 == nil
	}
	return false
}

// 删除cookie、
func (g GinCookie) Remove(context *gin.Context, key string) bool {
	context.SetCookie(key, "", -1, "/", context.Request.Host, false, true)
	return true
}

// 暴露结构体给外部调用
var Cookie = &GinCookie{}
